package net.zoneland.knowledge.service.impl.search;

import java.util.Optional;

import net.zoneland.knowledge.config.SearchStrategyConfig;
import net.zoneland.knowledge.constant.BizConstant;
import net.zoneland.knowledge.enums.DictParentEnum;
import net.zoneland.knowledge.enums.QueryTypeEnum;
import net.zoneland.knowledge.enums.TypeEnum;
import net.zoneland.knowledge.model.DictItem;
import net.zoneland.knowledge.model.QaQueryDto;
import net.zoneland.knowledge.model.QaResponse;
import net.zoneland.knowledge.service.DictItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 表情问答.
 *
 * @author: bcc
 * 2021/5/26
 */
@Service("searchOperationImplQueryEmoji")
public class SearchOperationImplQueryEmoji extends AbstractSearchOperation {

    @Autowired
    private DictItemService dictItemService;

    @Autowired
    private SearchStrategyConfig searchStrategyConfig;
    
    @Override
    public boolean needRun(final SearchDto searchDto) {
        if (!searchStrategyConfig.isEmoji()) {
            return false;
        }
        return !searchDto.isStopSearch() && isEmoji(searchDto);
    }

    /**
     * 是否表情问答
     * @param searchDto
     * @return
     */
    private boolean isEmoji(final SearchDto searchDto) {
        QaQueryDto qaQueryDto = searchDto.getQaQueryDto();
        String queryText = qaQueryDto.getQueryText();
        if(StringUtils.isBlank(queryText)) {
            return false;
        }
        //判断表情问答
        return QueryTypeEnum.SEARCH == qaQueryDto.getQaType() && queryText.startsWith("#") && queryText.endsWith(";");
    }


    @Override
    protected void doSearchOrDeal(final SearchDto searchDto) {
        QaQueryDto qaQueryDto = searchDto.getQaQueryDto();
        String queryText = qaQueryDto.getQueryText();
        String emoji = queryText;
        //确认是否多个存在表情，存在取第一个
        String[] emojiArr = emoji.split("#");
        if (emojiArr.length > 2) {
            emoji="#"+emoji.split("#")[1];
        }
        //匹配表情答案并替换机器人名称
        emoji = Optional.ofNullable(dictItemService.getByValue(DictParentEnum.EMOJI_TALK.getValue(),emoji))
                .map(DictItem::getDictName)
                .map(em -> em.replaceAll(BizConstant.REPLACE_ROBOT_NAME, qaQueryDto.getRobotName()))
                .orElse(emoji);
        searchDto.setStopDeal(true);
        searchDto.setStopSearch(true);
        QaResponse qaResponse = new QaResponse();
        qaResponse.setData(emoji);
        qaResponse.setType(TypeEnum.TEXT.getValue());
        searchDto.setQaResponse(qaResponse);
    }

}
